package com.htjc.integral.conversion.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.util.EntityUtils;
import org.springframework.ui.Model;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.commons.service.context.spring.config.CustomizedPropertyPlaceholderConfigurer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.htjc.integral.conversion.enums.SgccMallConstant;
import com.htjc.integral.model.conversion.EcPartner;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "exchangeLogger")
@SuppressWarnings("restriction")
public class SgccMallUtil {
	
//	private static final Logger log = Logger.getLogger(SgccMallUtil.class
//			.getCanonicalName());
	
	private static SgccMallUtil uniqueInstance = new SgccMallUtil();

	private SgccMallUtil() {
	}

	public static SgccMallUtil getInstance() {

		return uniqueInstance;

	}

	public String getConfValue(String key) {
		String userKey = null;
		if (StringUtils.isNotBlank(key)) {
			userKey = CustomizedPropertyPlaceholderConfigurer.getInstance()
					.getContextProperty(key);
		}
		return userKey;

	}

	public String getcookitInfo(HttpServletRequest request) {
		String cookieInfo = request.getHeader(SgccMallConstant.COOKIE);
		return cookieInfo;
	}

	/**
	 * 发送http get请求
	 * 
	 * @param url
	 *            ：请求的url
	 * @param cookie
	 *            ：需要在请求间传递的cookie信息
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String httpClientGetRequest(String url, String cookie)
			throws ClientProtocolException, IOException {
		Request get = Request.Get(url).connectTimeout(10000).socketTimeout(10000);
		get.setHeader(SgccMallConstant.COOKIE, cookie);
		return get.execute().returnContent().asString();
	}
	
	/**
	 * 发送http post请求
	 * 
	 * @param param
	 *            ：请求的参数
	 * @param cookie
	 *            ：需要在请求间传递的cookie信息
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String httpClientPostRequest(HttpServletRequest request, String cookie, Map<String, Object> param)
			throws ClientProtocolException, IOException {
		String message = "";
		if (param != null) {
			String url = getConfValue((String)param.get("domain"));
			String domainUrl = url + (String)param.get("funName");
//			String delUrl = "http://localhost/cart/showCart/addCart";
			Form myForm = Form.form();
			myForm.add("data", (String)param.get("data"));
			Request post = Request.Post(domainUrl);
			//将请求中的cookie封装到到HttpClient的Request，同时session也传递过来了
			post.addHeader("cookie", request.getHeader("cookie"));
			Response response = post.bodyForm(myForm.build()).connectTimeout(10000).socketTimeout(10000).execute();
			HttpResponse returnResponse = response.returnResponse();
			HttpEntity entity = returnResponse.getEntity();
			message = EntityUtils.toString(entity);
		}
		return message;
	}

	// 截取字符串
	public String subString(String str) {
		if (str == null || str == "") {
			return "";
		}
		return str.substring(0, str.length() > 10 ? 10 : str.length());
	}

	// 将 str = "Mon May 05 19:42:40 CST 2014";格式到yyyy-MM-dd HH:mm:ss E
	public String dateFormatWeek(Date date) {
		SimpleDateFormat dateformat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss E");
		String str = dateformat.format(date);

		return str;
	}

	// 将 str = "Mon May 05 19:42:40 CST 2014";格式到yyyy-MM-dd HH:mm:ss E
	public String dateFormatWeekToYTD(Date date) {
		SimpleDateFormat dateformat = new SimpleDateFormat(
				"yyyy年MM月dd日 HH时mm分ss秒 E ");
		String str = dateformat.format(date);

		return str;
	}

	// 将 str = "Mon May 05 19:42:40 CST 2014";格式的字符串转化为date
	public String dateFormat(Date date) {
		// Date date = parse(str, "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str = format1.format(date);

		return str;
	}

	public String dateFormatShort(Date date) {
		String str = "";
		if (date != null) {
			// Date date = parse(str, "EEE MMM dd HH:mm:ss zzz yyyy",
			// Locale.US);
			DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
			str = format1.format(date);
		}

		return str;
	}

	public static Date parse(String str, String pattern, Locale locale) {
		if (str == null || pattern == null) {
			return null;
		}
		try {
			return new SimpleDateFormat(pattern, locale).parse(str);
		} catch (ParseException e) {
			log.error("", e);
		}
		return null;
	}

	public static String format(Date date, String pattern, Locale locale) {
		if (date == null || pattern == null) {
			return null;
		}
		return new SimpleDateFormat(pattern, locale).format(date);
	}

	// 将字符串转化成Date
	public static Date stringtoDate(String str) throws ParseException {
		Date date = null;
		if (str != "") {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd");
			date = simpleDateFormat.parse(str);
		}
		return date;
	}

	// 将价钱字符串转换成BigDecimal
	public BigDecimal stringToBigDecimal(String str) {
		if (str == "" || str == null) {
			str = "0.00";
		}
		// 构造以字符串内容为值的BigDecimal类型的变量bd
		BigDecimal bd = new BigDecimal(str);
		// 设置小数位数，第一个变量是小数位数，第二个变量是取舍方法(四舍五入)
		// bd=bd.setScale(2, BigDecimal.ROUND_HALF_UP);

		return bd;
	}

	public String getErrorMsg(Exception e) {
		String errorMsg = "";
		Throwable cause = e.getCause();
		if (cause != null && StringUtils.isNotBlank(cause.getMessage())) {
			errorMsg = e.getCause().getMessage();
		} else if (StringUtils.isNotBlank(e.getMessage())) {
			errorMsg = e.getMessage();
		} else {

		}
		return errorMsg;
	}

	public String getContextPath(String contextPathStr) {
		// 获得文件保存路径
		String contextPath = "";
		contextPath = System.getProperty(contextPathStr);
		return contextPath;
	}

	public String getCookieValue(String name, HttpServletRequest request) {
		String userData = "";
		if (StringUtils.isNotBlank(name)) {
			String cookies = request.getHeader("Cookie");
			String[] cookie = cookies.split(";");
			Map<String, String> cookieMap = new HashMap<String, String>();
			for (String tempCookie : cookie) {
				String[] _cookie = tempCookie.split("=");
				cookieMap.put(_cookie[0].trim(), _cookie[1]);
				
			}
			userData = (String) cookieMap.get(name);
			log.debug("cookieName" + name);
			log.debug("cookieValue" + userData);
//			Cookie[] cookies = request.getCookies();
//			if (null != cookies) {
//				for (Cookie cookie : cookies) {
//					if (null != cookie.getName()) {
//						if (name.trim().equals(cookie.getName())) {
//							userData = cookie.getValue();
//							return userData;
//						}
//					}
//				}
//			}
		}
		return userData;

	}
	
	/*
	 * 输出json对象
	 */
	public void outputJSONResult(HttpServletResponse response, Object object) {
		PrintWriter out = null;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		try {
			ObjectMapper om = new ObjectMapper();
			out = response.getWriter();
			om.writeValue(out, object);
			out.flush();
		} catch (Exception e) {
			log.error("", e);
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
	
	public ServletContext getServletContext(HttpServletRequest request){
		ServletContext context = request.getSession().getServletContext();    
		return context;
	}
	
	public WebApplicationContext getWebApplicationContext(ServletContext context){
		
		WebApplicationContext ctx  = WebApplicationContextUtils.getWebApplicationContext(context); 
		return ctx;
	}
	
	public String getBean(WebApplicationContext ctx, String beanName){
		return (String) ctx.getBean(beanName);
	}
	
	public HashMap<String,String> makeMemberInfo(EcPartner ecPartner){
		
		HashMap<String,String> map = new HashMap<String, String>();
		
		map.put("partnerId", ecPartner.getPartnerId());
		map.put("loginAccount", ecPartner.getPartnerId());
		map.put("userType", ecPartner.getUserType());
		map.put("password", ecPartner.getPassword());
		map.put("mobile", ecPartner.getMobile());
		map.put("name", ecPartner.getName());
		map.put("email", ecPartner.getEmail());
		map.put("idcard", ecPartner.getIdcard());
		map.put("companyName", ecPartner.getCompanyName());
		map.put("organizationCode", ecPartner.getOrganizationCode());
		map.put("businessLicense", ecPartner.getBusinessLicense());
		map.put("taxregisterLicense", ecPartner.getTaxregisterLicense());
		map.put("itins", ecPartner.getItins());
		map.put("bankAccount", ecPartner.getBankAccount());
		map.put("accno", ecPartner.getAccno());
		map.put("contactPerson", ecPartner.getContactPerson());
		map.put("contactMobile", ecPartner.getContactMobile());
				
		return map;		
	}
	/**
	 * 检查图片大小、格式是否符合要求
	 * @param mufile 文件对象
	 * @param size 图片大小 单位MB
	 * @param model 模型
	 * @return true or false
	 */
	public static  boolean  checkImage(MultipartFile mufile,long size,Model model){  
		if (mufile.isEmpty()) {
			if( !mufile.getOriginalFilename().isEmpty()){
				model.addAttribute("success",false);
				model.addAttribute("errorMsg", "文件大小不可为0KB，请重新上传");
				return false;
			}
		}
		String name = mufile.getOriginalFilename();
		int len = mufile.getOriginalFilename().length();
	int index = name.lastIndexOf(".");
	if(index<0){
	    model.addAttribute("success",false);
		model.addAttribute("errorMsg", "请上传有扩展名的图片文件");
		return false;
	}else{
		String nameFormat =name.substring(index,len).toLowerCase();
		if(!nameFormat.matches("\\.(jpg|gif|png)+$")){
			   model.addAttribute("success",false);
				model.addAttribute("errorMsg", "图片格式错误，请重新上传");
				return false;
		}else{
			if (mufile.getSize() > 1024 * 1024 *size) {//超过6M 1024 * 1024 * 6
				 model.addAttribute("success",false);
				 model.addAttribute("errorMsg", "图片大小不能超过"+size+"M");
					return false;
			} else{				 
			}
		}
	}
		return true;
	}
	/**
	 * 检查图片大小、格式是否符合要求 APP 接口调用 
	 * @param mufile 文件对象
	 * @param size 图片大小 单位MB
	 * @param model 模型
	 * @return checkImageMessage: success ：格式验证成功，其他为对应的错误信息
	 */
	public static  String  checkImage2(MultipartFile mufile,long size){   
		String checkImageMessage="success";
		if (mufile.isEmpty()) {
			if( !mufile.getOriginalFilename().isEmpty()){				
				checkImageMessage="文件大小不可为0KB，请重新上传";
			}
		}
		String name = mufile.getOriginalFilename();
		int len = mufile.getOriginalFilename().length();
	int index = name.lastIndexOf(".");
	if(index<0){   
		checkImageMessage="请上传有扩展名的图片文件";
	}else{
		String nameFormat =name.substring(index,len).toLowerCase();
		if(!nameFormat.matches("\\.(jpg|gif|png)+$")){			
			checkImageMessage="图片格式错误，请重新上传";
		}else{
			if (mufile.getSize() > 1024 * 1024 *size) {//超过6M 1024 * 1024 * 6				
				checkImageMessage="图片大小不能超过"+size+"M";
			} else{				 
			}
		}
	}
	return checkImageMessage;
	}
	/**
	 * 加密
	 */
	public static String getBase64Encode(String s) {
		if (StringUtils.isBlank(s))
			return null;
		String result = "";
		BASE64Encoder encoder = new BASE64Encoder();  
		try {
			result = encoder.encodeBuffer(s.getBytes(SgccMallConstant.CODE)).trim();
		} catch (UnsupportedEncodingException e) {
			log.error("", e);
			return null;
		}
		return result;
	}
	/**
	 * 解密
	 */
	public static String getBase64Decode(String s) {
		if (StringUtils.isBlank(s))
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			return new String(decoder.decodeBuffer(s),SgccMallConstant.CODE);
		} catch (Exception e) {
			log.error("", e);
			return null;
		}
	}
	
	/**
	 * 格式化json字符串
	 */
	public static String formatToJsonP(String jsonString, String callback) {
		if (callback != null) {
			jsonString = callback + "(" + jsonString + ")";
		} else {
			jsonString = "(" + jsonString + ")";
		}
		return jsonString;
	}
}
